import * as THREE from 'three';
import { gsap } from 'gsap';
import { BaseScene } from './BaseScene.js';

export class ModelScene extends BaseScene {
    constructor(app, index) {
        super(app, index);
        this.name = '模型场景';
        // 模型数组
        this.models = [];
        this.complexShapes = [];
        
        // 场景特定设置
        this.cameraPosition.set(0, 3, 12);
        this.cameraTarget.set(0, 0, 0);
        
        // 动画参数
        this.morphSpeed = 0.003;
        this.rotationSpeed = 0.005;
        
        // 环境设置
        this.ambientLightIntensity = 0.6;
        this.directionalLightIntensity = 1.2;
    }
    
    async createObjects() {
        // 创建复杂几何模型
        this.createComplexModels();
        
        // 创建变形动画模型
        this.createMorphingModels();
        
        // 创建程序生成的建筑
        this.createProceduralBuildings();
        
        // 创建环境装饰
        this.createEnvironmentDecorations();
        
        // 设置模型动画
        this.setupModelAnimations();
    }
    
    createComplexModels() {
        // 创建复杂的多面体
        this.createIcosahedron();
        this.createParametricSurface();
        this.createKnotGeometry();
    }
    
    createIcosahedron() {
        // 多层级二十面体
        const geometry = new THREE.IcosahedronGeometry(2, 2);
        
        // 创建多层材质
        const materials = [
            new THREE.MeshPhongMaterial({ 
                color: 0x4fc3f7, 
                transparent: true, 
                opacity: 0.8,
                side: THREE.DoubleSide
            }),
            new THREE.MeshBasicMaterial({ 
                color: 0x29b6f6, 
                wireframe: true,
                transparent: true,
                opacity: 0.3
            })
        ];
        
        const solidMesh = new THREE.Mesh(geometry, materials[0]);
        solidMesh.position.set(-4, 2, 0);
        solidMesh.castShadow = true;
        solidMesh.receiveShadow = true;
        
        const wireframeMesh = new THREE.Mesh(geometry, materials[1]);
        wireframeMesh.position.set(-4, 2, 0);
        wireframeMesh.scale.setScalar(1.05);
        
        this.addObject(solidMesh);
        this.addObject(wireframeMesh);
        
        this.models.push({
            solid: solidMesh,
            wireframe: wireframeMesh,
            type: 'icosahedron'
        });
    }
    
    createParametricSurface() {
        // 参数曲面 - Klein瓶变体，手动创建几何体
        const geometry = new THREE.BufferGeometry();
        const vertices = [];
        const indices = [];
        const normals = [];
        const uvs = [];
        
        const uSegments = 50;
        const vSegments = 50;
        
        // 生成顶点
        for (let i = 0; i <= uSegments; i++) {
            for (let j = 0; j <= vSegments; j++) {
                const u = (i / uSegments) * Math.PI;
                const v = (j / vSegments) * 2 * Math.PI;
                
                const a = 3;
                const n = 2;
                
                const x = a * (1 + Math.cos(u)) * Math.cos(v) * 0.3;
                const y = a * (1 + Math.cos(u)) * Math.sin(v) * 0.3;
                const z = (a * Math.sin(u) + n * Math.cos(v / 2) * Math.sin(u)) * 0.3;
                
                vertices.push(x, y, z);
                
                // UV坐标
                uvs.push(i / uSegments, j / vSegments);
                
                // 简单的法线计算
                const normal = new THREE.Vector3(x, y, z).normalize();
                normals.push(normal.x, normal.y, normal.z);
            }
        }
        
        // 生成面索引
        for (let i = 0; i < uSegments; i++) {
            for (let j = 0; j < vSegments; j++) {
                const a = i * (vSegments + 1) + j;
                const b = i * (vSegments + 1) + j + 1;
                const c = (i + 1) * (vSegments + 1) + j + 1;
                const d = (i + 1) * (vSegments + 1) + j;
                
                indices.push(a, b, d);
                indices.push(b, c, d);
            }
        }
        
        geometry.setIndex(indices);
        geometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
        geometry.setAttribute('normal', new THREE.Float32BufferAttribute(normals, 3));
        geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2));
        geometry.computeVertexNormals();
        
        const material = new THREE.MeshPhongMaterial({
            color: 0xe91e63,
            shininess: 100,
            transparent: true,
            opacity: 0.9,
            side: THREE.DoubleSide
        });
        
        const mesh = new THREE.Mesh(geometry, material);
        mesh.position.set(0, 1, 0);
        mesh.castShadow = true;
        mesh.receiveShadow = true;
        
        this.addObject(mesh);
        this.models.push({
            object: mesh,
            type: 'parametric'
        });
    }
    
    createKnotGeometry() {
        // 环面结
        const geometry = new THREE.TorusKnotGeometry(1.5, 0.4, 100, 16, 3, 4);
        
        // 创建渐变材质
        const material = new THREE.MeshPhongMaterial({
            color: 0x9c27b0,
            shininess: 150,
            transparent: true,
            opacity: 0.95
        });
        
        const mesh = new THREE.Mesh(geometry, material);
        mesh.position.set(4, 2, 0);
        mesh.castShadow = true;
        mesh.receiveShadow = true;
        
        this.addObject(mesh);
        this.models.push({
            object: mesh,
            type: 'knot'
        });
    }
    
    createMorphingModels() {
        // 创建变形几何体
        this.createMorphingShape();
    }
    
    createMorphingShape() {
        // 基础几何体 - 使用球体作为基础
        const sphereGeometry = new THREE.SphereGeometry(1.2, 16, 16); // 减少细分以提高性能
        
        // 创建变形几何体
        const geometry = sphereGeometry.clone();
        
        // 创建变形目标 - 将球体变形为立方体样式
        const positions = geometry.attributes.position.array;
        const morphPositions = new Float32Array(positions.length);
        
        // 将球体顶点变形为更接近立方体的形状
        for (let i = 0; i < positions.length; i += 3) {
            const x = positions[i];
            const y = positions[i + 1];
            const z = positions[i + 2];
            
            // 创建立方体样式的变形
            const factor = 1.5;
            morphPositions[i] = Math.sign(x) * Math.pow(Math.abs(x), 0.5) * factor;
            morphPositions[i + 1] = Math.sign(y) * Math.pow(Math.abs(y), 0.5) * factor;
            morphPositions[i + 2] = Math.sign(z) * Math.pow(Math.abs(z), 0.5) * factor;
        }
        
        // 设置变形属性
        geometry.morphAttributes.position = [];
        geometry.morphAttributes.position[0] = new THREE.Float32BufferAttribute(morphPositions, 3);
        
        const material = new THREE.MeshPhongMaterial({
            color: 0xff5722,
            morphTargets: true,
            shininess: 80
        });
        
        const mesh = new THREE.Mesh(geometry, material);
        mesh.position.set(0, -2, 0);
        mesh.castShadow = true;
        mesh.receiveShadow = true;
        
        this.addObject(mesh);
        this.complexShapes.push({
            object: mesh,
            type: 'morphing',
            morphInfluence: 0
        });
    }
    
    createProceduralBuildings() {
        // 程序生成的简单建筑群
        const buildingCount = 8;
        const buildings = [];
        
        for (let i = 0; i < buildingCount; i++) {
            const width = Math.random() * 1 + 0.5;
            const height = Math.random() * 3 + 1;
            const depth = Math.random() * 1 + 0.5;
            
            const geometry = new THREE.BoxGeometry(width, height, depth);
            const material = new THREE.MeshPhongMaterial({
                color: new THREE.Color().setHSL(Math.random(), 0.5, 0.6)
            });
            
            const building = new THREE.Mesh(geometry, material);
            
            // 随机位置（围成圆形）
            const angle = (i / buildingCount) * Math.PI * 2;
            const radius = 8;
            building.position.set(
                Math.cos(angle) * radius + (Math.random() - 0.5) * 2,
                height / 2 - 3,
                Math.sin(angle) * radius + (Math.random() - 0.5) * 2
            );
            
            building.castShadow = true;
            building.receiveShadow = true;
            
            this.addObject(building);
            buildings.push(building);
        }
        
        this.models.push({
            objects: buildings,
            type: 'buildings'
        });
    }
    
    createEnvironmentDecorations() {
        // 创建地面
        this.createGround();
        
        // 创建环境光带
        this.createLightRings();
        
        // 创建飘浮的装饰元素
        this.createFloatingDecorations();
    }
    
    createGround() {
        const geometry = new THREE.PlaneGeometry(30, 30, 50, 50);
        
        // 给地面添加一些起伏
        const positions = geometry.attributes.position.array;
        for (let i = 2; i < positions.length; i += 3) {
            positions[i] = Math.sin(positions[i - 2] * 0.3) * Math.cos(positions[i - 1] * 0.3) * 0.5;
        }
        geometry.attributes.position.needsUpdate = true;
        geometry.computeVertexNormals();
        
        const material = new THREE.MeshPhongMaterial({
            color: 0x2e2e2e,
            shininess: 10
        });
        
        const ground = new THREE.Mesh(geometry, material);
        ground.rotation.x = -Math.PI / 2;
        ground.position.y = -4;
        ground.receiveShadow = true;
        
        this.addObject(ground);
    }
    
    createLightRings() {
        // 创建发光环
        for (let i = 0; i < 3; i++) {
            const geometry = new THREE.TorusGeometry(3 + i * 2, 0.1, 8, 32);
            const material = new THREE.MeshBasicMaterial({
                color: new THREE.Color().setHSL(i / 3, 1.0, 0.5),
                transparent: true,
                opacity: 0.6
            });
            
            const ring = new THREE.Mesh(geometry, material);
            ring.position.set(0, -3 + i * 0.2, 0);
            ring.rotation.x = Math.PI / 2;
            
            this.addObject(ring);
            this.models.push({
                object: ring,
                type: 'lightRing',
                index: i
            });
        }
    }
    
    createFloatingDecorations() {
        // 创建飘浮的小装饰物
        const decorationCount = 15;
        
        for (let i = 0; i < decorationCount; i++) {
            const shapes = [
                () => new THREE.TetrahedronGeometry(0.2),
                () => new THREE.OctahedronGeometry(0.15),
                () => new THREE.DodecahedronGeometry(0.1)
            ];
            
            const randomShape = shapes[Math.floor(Math.random() * shapes.length)];
            const geometry = randomShape();
            
            const material = new THREE.MeshPhongMaterial({
                color: new THREE.Color().setHSL(Math.random(), 0.8, 0.7),
                transparent: true,
                opacity: 0.8
            });
            
            const decoration = new THREE.Mesh(geometry, material);
            decoration.position.set(
                (Math.random() - 0.5) * 20,
                Math.random() * 8 - 2,
                (Math.random() - 0.5) * 20
            );
            
            decoration.userData.floatSpeed = Math.random() * 0.02 + 0.01;
            decoration.userData.rotationSpeed = (Math.random() - 0.5) * 0.05;
            decoration.userData.originalY = decoration.position.y;
            
            this.addObject(decoration);
            this.complexShapes.push({
                object: decoration,
                type: 'decoration'
            });
        }
    }
    
    setupModelAnimations() {
        const animation = {
            update: ((time) => {
                this.updateComplexModels(time);
                this.updateMorphingModels(time);
                this.updateFloatingDecorations(time);
                this.updateLightRings(time);
            }).bind(this) // 绑定正确的this上下文
        };
        
        this.animations.push(animation);
    }
    
    updateComplexModels(time) {
        this.models.forEach(model => {
            switch (model.type) {
                case 'icosahedron':
                    model.solid.rotation.x = time * this.rotationSpeed;
                    model.solid.rotation.y = time * this.rotationSpeed * 1.3;
                    model.wireframe.rotation.x = time * this.rotationSpeed * 0.7;
                    model.wireframe.rotation.y = time * this.rotationSpeed * 0.9;
                    break;
                    
                case 'parametric':
                    model.object.rotation.z = time * this.rotationSpeed * 0.5;
                    model.object.rotation.y = time * this.rotationSpeed * 2;
                    break;
                    
                case 'knot':
                    model.object.rotation.x = time * this.rotationSpeed * 1.5;
                    model.object.rotation.z = time * this.rotationSpeed;
                    break;
            }
        });
    }
    
    updateMorphingModels(time) {
        this.complexShapes.forEach(shape => {
            if (shape.type === 'morphing') {
                // 变形动画
                shape.morphInfluence = (Math.sin(time * this.morphSpeed) + 1) / 2;
                shape.object.morphTargetInfluences[0] = shape.morphInfluence;
                
                // 旋转
                shape.object.rotation.y = time * this.rotationSpeed;
            }
        });
    }
    
    updateFloatingDecorations(time) {
        this.complexShapes.forEach(shape => {
            if (shape.type === 'decoration') {
                const obj = shape.object;
                
                // 浮动动画
                obj.position.y = obj.userData.originalY + Math.sin(time * obj.userData.floatSpeed) * 0.5;
                
                // 旋转动画
                obj.rotation.x += obj.userData.rotationSpeed;
                obj.rotation.y += obj.userData.rotationSpeed * 0.7;
                obj.rotation.z += obj.userData.rotationSpeed * 0.3;
            }
        });
    }
    
    updateLightRings(time) {
        this.models.forEach(model => {
            if (model.type === 'lightRing') {
                model.object.rotation.z = time * 0.001 * (model.index + 1);
                
                // 脉冲效果
                const pulse = Math.sin(time * 0.003 + model.index) * 0.2 + 1;
                model.object.scale.setScalar(pulse);
                
                // 颜色变化
                const hue = (time * 0.0005 + model.index / 3) % 1;
                model.object.material.color.setHSL(hue, 1.0, 0.5);
            }
        });
    }
    
    adjustParticleCount(factor) {
        // 调整装饰物的数量和复杂度
        this.complexShapes.forEach(shape => {
            if (shape.type === 'decoration') {
                shape.object.visible = Math.random() < factor;
            }
        });
        
        // 调整光环的透明度
        this.models.forEach(model => {
            if (model.type === 'lightRing') {
                model.object.material.opacity = 0.6 * factor;
            }
        });
    }
    
    updateObjects() {
        super.updateObjects();
        
        // 动态调整环境光照
        const time = performance.now() * 0.001;
        
        if (this.directionalLight) {
            // 光源围绕场景旋转
            const radius = 8;
            this.directionalLight.position.x = Math.cos(time * 0.3) * radius;
            this.directionalLight.position.z = Math.sin(time * 0.3) * radius;
            this.directionalLight.position.y = 5 + Math.sin(time * 0.2) * 2;
        }
    }
}
